package com.kmxd.ams.controller.oss;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import com.kmxd.ams.client.oss.IEfileRecordSvc;
import com.kmxd.ams.client.oss.vo.EfileRecordVO;
import com.kmxd.ams.core.common.enums.LogLevelEnum;
import com.kmxd.ams.core.common.enums.LogTypeEnum;
import com.kmxd.ams.core.log.annotation.AutoLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 公共附件表 前端控制器
 *
 * @author ZuoLG
 * @since 2022-07-25
 */
@RestController
@Tag(name = "PDF附件预览")
@RequestMapping("/oss/preview")
@AllArgsConstructor
@Slf4j
public class PdfPreviewCtl {

  private IEfileRecordSvc efileRecordService;

  /** 文件预览 */
  @Operation(summary = "文件预览")
  @GetMapping("/pdfPreview")
  @AutoLog(
      module = "文件管理",
      type = LogTypeEnum.ELECTRONIC_RECORD,
      level = LogLevelEnum.HIGH,
      title = "文件预览")
  @SneakyThrows
  public void pdfPreview(Long id, HttpServletResponse response) {
    EfileRecordVO recordVO = efileRecordService.view(id);
    response.reset();
    response.setContentType("application/octet-stream;charset=UTF-8");
    response.setCharacterEncoding("UTF-8");
    response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
    response.setHeader(
        "Content-Disposition",
        "attachment; filename="
            + URLEncoder.encode(recordVO.getTitle(), StandardCharsets.UTF_8.name()));
    response.addHeader("Content-Length", String.valueOf(recordVO.getFile().length()));
    try (ServletOutputStream out = response.getOutputStream()) {
      IoUtil.write(out, true, FileUtil.readBytes(recordVO.getFile()));
    } catch (IOException e) {
      log.error("{} 文件下载失败", recordVO, e);
    }
  }
}
